import {DataRouter} from "../frame/dataSource/DataRouter";
import {MaterialInfo} from "../type/Type";
import {TaskController} from "../controller/TaskController";
import {ItemType} from "../frame/dataSource/DataModel";
import {AbilityController} from "../controller/AbilityController";
import {GlobalEnv} from "../utils/GlobalEnv";
import {BroadcastRequest, BroadcastType, ControllerNo,} from "../controller/model/ControllerOpt";
import {UnitController} from "../controller/UnitController";
import {ControllerBroadcast} from "../controller/ControllerBroadcast";
import Configer from "../frame/apiModel/config/Configer";
import {FinalKey} from "../constant/FinalConstant";
import {GoodController} from "../controller/GoodController";
import {Logger} from "../frame/apiModel/config/Logger";
import {TriggerFactory} from "../frame/TriggerFactory";
import {UnitModel} from "../frame/apiModel/adapterModel/model3/UnitModel";
import {ItemModel} from "../frame/apiModel/adapterModel/model3/ItemModel";
import {PlayerModel} from "../frame/apiModel/adapterModel/model4/PlayerModel";
import {CodeUtil} from "../frame/codeAdapter/CodeUtil";
import {PlayerFactory} from "../frame/PlayerFactory";
import {ModelFactory} from "../frame/apiModel/adapterModel/model5/ModelFactory";
import {ConfigKey} from "../constant/ConfigConstant";
import {Util} from "../utils/Util";
import {AchievementController} from "../controller/AchievementController";
import {ModelType} from "../frame/apiModel/adapter/adapterInterface/model5/IModelFactory";
import {useItemCallBack} from "./UseItemTrigger";

export function getItemTrigger() {
    const getItem = function (this: void, getUnit: UnitModel, item: ItemModel, activePlayer: PlayerModel, seller?: UnitModel) {
        if (item) {
        } else {
            return;
        }
        const itemIdStr = item.strId;
        const itemData = DataRouter.getItemDataByItemId(itemIdStr);

        if (itemData) {
            const useUnit = getUnit;
            const playerCheck = activePlayer.isNotEndPlaying();
            const integral = itemData.integral;
            const cost = itemData.goldcost;
            if (playerCheck) {
            } else {
                return;
            }

            const bGet = TaskController.getInstance().checkGet(useUnit, item);
            if (bGet) {
            } else {
                return;
            }

            let success = TaskController.getInstance().itemCheckGetConditions(useUnit, activePlayer, itemIdStr);
            let bUse = false;

            if (seller) {
                const ret = AchievementController.getInstance().checkIntegral(activePlayer, integral)
                if (ret) {
                } else {
                    ModelFactory.getInstance().unitRemoveItem(useUnit, item);
                    return;
                }
            }

            if (success) {

                const getSuccessTip = itemData.getSuccessTip;
                if (getSuccessTip) {
                    Logger.toastProduct(getSuccessTip, activePlayer);
                }

                const useQualityMix = Configer.getConfig(ConfigKey.useQualityMix);
                const materialInfos: MaterialInfo[] = TaskController.getInstance().getMixGoodsInfoInUnitBag(getUnit, item);
                if (!CodeUtil.isNullOrZero(useQualityMix)) {
                    const mixQualityRet = TaskController.getInstance().toMixItemByQuality(getUnit, materialInfos);
                    if (mixQualityRet) {
                        if (item) {
                            ModelFactory.getInstance().unitRemoveItem(useUnit, item);
                        }
                        bUse = true;
                    }
                }

                if (bUse) {
                    return;
                }

                const mixRet = TaskController.getInstance().toMixItemByMixData(getUnit, item, materialInfos);
                if (mixRet) {
                    if (item) {
                        ModelFactory.getInstance().unitRemoveItem(useUnit, item);
                    }
                    bUse = true;
                }

                if (bUse) {
                    return;
                }

                /**
                 * 用来返还未生效道具的消耗
                 * @param success
                 */
                const successFun = (success: boolean, bConsume: boolean) => {
                    // let needRemove = false;
                    let bUse = bConsume
                    if (success) {
                        if (seller) {
                            AchievementController.getInstance().consumeIntegral(activePlayer, integral);
                        }
                        // if (bConsume) {
                        //     needRemove = true;
                        // }
                    } else {
                        if (bConsume) {
                            if (seller) {
                                activePlayer.cosumeGold(-cost);
                            }
                            // needRemove = true;
                        } else {
                            getUnit.dropItem(item, getUnit.loc)
                            bUse = true;
                        }
                    }
                    // if (needRemove) {
                    //     UnitController.getInstance().itemDeadRemove(item);
                    //     ModelFactory.getInstance().unitRemoveItem(useUnit, item);
                    // }
                    return bUse
                }

                const useByTypeRet = useItemByType(useUnit, item, activePlayer, seller);
                const bConsumeByType = useByTypeRet.bConsume;
                const successByType = useByTypeRet.success;

                bUse = successFun(successByType, bConsumeByType)

                if (bUse) {
                    return;
                }

                if (!CodeUtil.isNullOrZero(itemData.stackable)) {
                    getItemToNum(useUnit, item);
                }

                if (!CodeUtil.isNullOrZero(itemData.powerup)) {
                    useItemCallBack(useUnit, item, activePlayer);
                    ModelFactory.getInstance().unitRemoveItem(useUnit, item)
                }
            } else {
                getUnit.dropItem(item, getUnit.loc);
                const failedTip = itemData.getFailedTip;
                if (failedTip) {
                    Logger.toastProduct(failedTip, activePlayer);
                }
            }
        }
    }
    TriggerFactory.getInstance().registerUnitGetItem(getItem)
}
export function getEquip (getUnit: UnitModel, item: ItemModel, activePlayer: PlayerModel) {
    let getEquipRet;
    const useBag = Configer.getConfig(ConfigKey.useGoodsBar);
    if (!CodeUtil.isNullOrZero(useBag)) {
        getEquipRet = GoodController.getInstance().insertShowItemToBag(activePlayer, item);
        if (getEquipRet) {
        } else {
            item.loc = getUnit.loc;
            Logger.toastProduct('背包已满', activePlayer);
        }
    } else {
        const usePositionCheck = Configer.getConfig(ConfigKey.usePositionCheck)
        if (!CodeUtil.isNullOrZero(usePositionCheck)) {
            const isHero = GlobalEnv.isInHeroGroup(getUnit);
            if (isHero) {
                getEquipRet = checkEquip(getUnit, item);
            } else {
                getEquipRet = true;
            }
        } else {
            getEquipRet = true;
        }
    }
    if (getEquipRet) {
    } else {
        const loc = getUnit.loc;
        getUnit.dropItem(item, loc);
    }
    return true;
}
export function useItemByType(useUnit: UnitModel, item: ItemModel, activePlayer: PlayerModel, seller?: UnitModel): { bConsume: boolean, success: boolean } {
    let bConsume = false;
    let success = true;
    const itemType = item?.template?.item_type;
    switch (itemType) {
        case ItemType.equip: {
            success = getEquip(useUnit, item, activePlayer)
            break;
        }
    }
    return { bConsume: bConsume, success };
}



function getItemToNum(unit: UnitModel, item: ItemModel) {
    const strId = item.strId;
    unit.mapItems((slotItem) => {
        if (slotItem.equal(item)) {
            return false;
        }
        if (slotItem.strId === strId) {
            const tempNum = item.charges;
            const newNum = slotItem.charges + tempNum;
            slotItem.charges = newNum;
            GoodController.getInstance().removeGoods(unit, item);
            return true;
        }
        return false;
    })

}

function checkEquip(unit: UnitModel, item: ItemModel): boolean {
    const itemStrId = item.strId;
    const player = PlayerFactory.getInstance().getUnitOwner(unit);
    const goodData = DataRouter.getItemDataByItemId(itemStrId);
    if (goodData) {
    } else {
        Logger.toastError('捡起了一个不存在的物品');
        return false;
    }
    const goodPosition = goodData?.position;
    Logger.toastSys(`装备部位:${goodPosition}`, player)
    let bHave = false, positionStr;
    let equipNum = 0
    unit.mapItems((slotItem) => {
        const goodId = slotItem.strId;
        const tempData = DataRouter.getItemDataByItemId(goodId);
        if (tempData) {
            const tempPosition = tempData.position;
            if (!CodeUtil.isNullOrZero(tempPosition) && tempPosition === goodPosition) {
                if (goodId === itemStrId) {
                    if (equipNum >= 1) {
                        positionStr = '相同装备';
                        bHave = true;
                    }
                    equipNum = equipNum + 1;
                } else {
                    positionStr = Util.getNameByPosition(tempPosition);
                    bHave = true
                }
            }
        }
        if (bHave) {
            Logger.toastProduct(`不能携带两件${positionStr}`, player)
            const loc = unit.loc;
            unit.dropItem(item, loc)
            return true;
        }
        return false
    })
    return true;
}